package com.youhui.weixin.utils.weixin;

import com.thoughtworks.xstream.XStream;
import com.youhui.weixin.common.exception.MythException;
import com.youhui.weixin.common.info.MythExceptionList;
import com.youhui.weixin.weixin.domain.*;
import lombok.extern.log4j.Log4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.youhui.weixin.utils.weixin.WXConfig.*;
/**
 * Created by https://github.com/kuangcp on 17-10-14  下午9:02
 * 消息的工具类
 */
@Log4j
public class WXMessagesUtils {
    /**
     * 装载TEXT数据
     * @param toUserName 接收方
     * @param fromUserName 发送方
     * @param content 内容
     * @return XML字符串
     */
    public static String loadText(String toUserName, String fromUserName, String content){
        TextMsg text = new TextMsg();
        log.debug("回复内容："+text.toString());
        text.setContent(content);
        text.setMsgType(MESSAGE_TEXT);
        text.setToUserName(fromUserName);
        text.setFromUserName(toUserName);
        text.setCreateTime(new Date().getTime() + "");
        return textToXml(text);
    }

    /**
     * 图文消息
     */
    public static String loadNews(String toUserName, String fromUserName,
                                 List<News>newsList){
        NewsMsg newsMsg = new NewsMsg();
        newsMsg.setMsgType(WXConfig.MESSAGE_NEWS);
        newsMsg.setArticles(newsList);
        newsMsg.setArticleCount(newsList.size());
        newsMsg.setToUserName(fromUserName);
        newsMsg.setFromUserName(toUserName);
        newsMsg.setCreateTime(new Date().getTime() + "");
        return textToXml(newsMsg);
    }

    /**
     * 普通文本消息转为XML
     * @param text 文本
     * @return XML字符串
     */
    public static String textToXml(BaseMsg text){
        XStream xstream = new XStream();
        xstream.alias("xml", text.getClass());
        xstream.alias("item", News.class);
        String result = xstream.toXML(text);
        log.info(result);
        return result;
    }
    /**
     * request请求中XML转换为map
     * @param request HTTP的request请求
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws MythException {
        InputStream ins;
        try {
            ins = request.getInputStream();
        } catch (IOException e) {
            throw new MythException(MythExceptionList.REQUEST_FAILED, e, WXMessagesUtils.class);
        }
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        Document doc;
        try {
            doc = reader.read(ins);
        } catch (DocumentException e) {
            throw new MythException(MythExceptionList.REQUEST_READ_XML_FAILED, e, WXMessagesUtils.class);
        }
        Element root = doc.getRootElement();
        List list = root.elements();
        for (Object temp:list){
            Element temps = (Element) temp;
            map.put(temps.getName(), temps.getText());
        }
        try {
            ins.close();
        } catch (IOException e) {
            throw new MythException(MythExceptionList.CLOSE_IO_EXCEPTION, e, WXMessagesUtils.class);
        }
        return map;
    }
    /**
     * 图文消息转为XML
     * @param text 文本
     * @return XML的字符串
     */
    public static String newMessageToXml(NewsMsg text){
        XStream xstream = new XStream();
        xstream.alias("xml", text.getClass());
        xstream.alias("item", News.class);
        String result = xstream.toXML(text);
        log.debug("收到的内容："+result);
        return result;
    }


    /**
     * sha1 加密算法
     * @param origin 原始字符串
     * @return 返回加密字符串
     */
    public static String getSha1(String origin){
        char hex[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try{
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(origin.getBytes("UTF-8"));
            byte[] md = messageDigest.digest();
            int j = md.length;
            char []buff = new char[j*2];
            int k = 0;
            for (byte byte0 : md) {
                buff[k++] = hex[byte0 >>> 4 & 0xf];
                buff[k++] = hex[byte0 & 0xf];
            }
            return new String(buff);
        }catch (Exception e){
            return null;
        }
    }


}
